package com.lgx.mobile.rest.user;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.lgx.mobile.model.UserModel;
import com.lgx.right.entity.User;
import com.lgx.right.entity.UserExpand;
import com.lgx.right.service.IUserExpandService;
import com.lgx.right.service.IUserService;

/**
 * 
 * @author pengdeyi (king)
 *
 */
@Controller
@RequestMapping("/login")
public class LoginRestController {
	
	private static final Logger logger = Logger.getLogger(LoginRestController.class);

	@Autowired
	IUserService userService;
	
	public IUserService getUserService() {
		return userService;
	}
	
	@Autowired
	IUserExpandService userExpandService;

	public IUserExpandService getUserExpandService() {
		return userExpandService;
	}

	/**
	 * 用户登录
	 * @param username u is key
	 * @param password p is key
	 * @return 用户信息；0：用户不存在；1：参数异常，有参数为空
	 */
	@RequestMapping(value="/{u}/{p}",method=RequestMethod.GET)
	@ResponseBody
	public Object login(@PathVariable("u") String username,@PathVariable("p") String password){
		if(StringUtils.isNotBlank(username)&&StringUtils.isNotBlank(password)){
			UserModel userModel = new UserModel(null);
			User user = getUserService().loginUser(username, password);
			if(user!=null){
				UserExpand userExpand = getUserExpandService().findUserExpandByUserId(user.getId());
				if(userExpand != null){
					userModel.setDegree(userExpand.getDegree());
					userModel.setFunType(userExpand.getFunType());
					userModel.setLevel(userExpand.getLevel());
					userModel.setGiftRecord(userExpand.getGiftRecord());
				}
				userModel.setId(user.getId());
				userModel.setCardId(user.getCard().getId());
				userModel.setTrueName(user.getTruename());
				userModel.setScore(user.getCard().getScore());
				return userModel;
			}else{
				if(logger.isDebugEnabled()){
					logger.debug("login faild username and password is error");
				}
//				return "login faild please check username is exists";
				return "0";
			}
		}else{
			if(logger.isDebugEnabled()){
				logger.debug("login faild username and password is not filled");
			}
//			"login faild please check username and password is filled"
		    return "1";
		}
	}
}
